package service

import (
	"bgs/cache/redisImp"
	"bgs/conf"
	"bgs/db"
	sqlc "bgs/db/sqlc"
	"bgs/grpc/client"

	"bgs/util"
	"context"

	"go.uber.org/zap"
)

// SpokesmanService spokesman bizlogic
type SpokesmanServiceImp struct {
	dao    *db.PgDao
	slog   *zap.SugaredLogger
	vars   *conf.VarsSection
	proxy  *client.GrpcClientProxy
	cacher *cache.Adapter
}

// NewBrandService initialization
func NewSpokesmanServiceImp(
	pgdao *db.PgDao,
	slog *zap.SugaredLogger,
	vars *conf.VarsSection,
	proxy *client.GrpcClientProxy,
	adp *cache.Adapter,
) *SpokesmanServiceImp {
	return &SpokesmanServiceImp{
		dao:    pgdao,
		slog:   slog.With("module", "SpokesmanService"),
		vars:   vars,
		proxy:  proxy,
		cacher: adp,
	}
}

// GetSpokesman 获取用户的统计信息并返回
func (s *SpokesmanServiceImp) GetSpokesman(ctx context.Context, q *sqlc.Queries, withLock bool, spokesmanID int64) (spokesman sqlc.Spokesman, err error) {
	slog := util.NewContextLogger(ctx, s.slog)
	if withLock {
		spokesman, err = q.GetSpokesmanToLock(ctx, spokesmanID)
	} else {
		spokesman, err = q.GetSpokesman(ctx, spokesmanID)
	}

	if err != nil {
		return
	}
	slog.Infof("确保用户的统计信息并返回 ok")
	return
}

// UpdateSaleAmountSinceOrderPayed 新订单支付成功更新代言人代言的活动订单的销售金额(该订单必须是代言人代言活动的订单)
func (s *SpokesmanServiceImp) UpdateSaleAmountSinceOrderPayed(ctx context.Context, q *sqlc.Queries, orderPtr *sqlc.Order) (err error) {
	slog := util.NewContextLogger(ctx, s.slog)

	spokesmanLocked, err := s.GetSpokesman(ctx, q, true, orderPtr.SpokesmanID.Int64)
	if err != nil {
		return
	}
	slog.Infof("1、订单支付成功-确保获取锁定的代言人记录(%d) ok", spokesmanLocked.ID)

	saleAmount, err := q.AggrOrderSaleAmountBySpokesmanID(ctx, orderPtr.SpokesmanID)
	if err != nil {
		return
	}
	slog.Infof("2、统计当前订单支付成功后统计代言人销售总金额 ok")

	err = q.UpdateSpokesmanSaleAmount(ctx, sqlc.UpdateSpokesmanSaleAmountParams{
		ID:         spokesmanLocked.ID,
		SaleAmount: saleAmount,
	})
	if err != nil {
		return
	}

	slog.Infof("3、新订单支付成功更新代言人代言的活动订单的销售金额 ok")
	return
}

// UpdateEndorseActivityCountSinceActivityPublished 新代言活动成功发布后更新代言人的代言活动数
func (s *SpokesmanServiceImp) UpdateEndorseActivityCountSinceActivityPublished(ctx context.Context, q *sqlc.Queries, activityPtr *sqlc.Activity) (err error) {
	slog := util.NewContextLogger(ctx, s.slog)

	spokesmanLocked, err := s.GetSpokesman(ctx, q, true, activityPtr.SpokesmanID.Int64)
	if err != nil {
		return
	}
	slog.Infof("1、代言活动发布成功-确保获取锁定的代言人记录(%d) ok", spokesmanLocked.ID)

	endorseActivityCount, err := q.CountSpokesmanOwnActivitiesBySpokesmanID(ctx, activityPtr.SpokesmanID)
	if err != nil {
		return
	}
	slog.Infof("2、统计当前活动发布成功后统计代言人代言活动 ok")

	err = q.UpdateSpokesmanEndorseActivityCount(ctx, sqlc.UpdateSpokesmanEndorseActivityCountParams{
		ID:                   spokesmanLocked.ID,
		EndorseActivityCount: int32(endorseActivityCount),
	})
	if err != nil {
		return
	}

	slog.Infof("3、新代言活动成功发布后更新代言人的代言活动数 ok")
	return
}
